package me.bzcoder.easywebview.common

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import me.bzcoder.easywebview.utils.Tools
import me.bzcoder.easywebview.webinterface.IWebViewActivity

/**
 * WebViewClient
 *
 * @author : BaoZhou
 * @date : 2019/7/23 16:47
 */
class X5WebViewClient(private var mIWebPageView: IWebViewActivity?) : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        if (TextUtils.isEmpty(url)) {
            return false
        }
        if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
            // 可能有提示下载Apk文件
            if (url.contains(APK)) {
                handleOtherwise(url)
                return true
            }
            return false
        }
        handleOtherwise(url)
        return true
    }

    override fun onPageFinished(view: WebView, url: String) {
        if (!Tools.isNetworkConnected(webPageView!!.activity)) {
            webPageView!!.hideProgressBar()
        }
        webPageView!!.onPageFinished(view,url)

        webPageView!!.addImageClickListener(view)
        // html加载完成之后，添加监听图片的点击js函数
        super.onPageFinished(view, url)
    }

    override fun onReceivedError(
        view: WebView,
        errorCode: Int,
        description: String,
        failingUrl: String
    ) {
        super.onReceivedError(view, errorCode, description, failingUrl)
        if (errorCode == 404) {
            //用javascript隐藏系统定义的404页面信息
            val data = "Page NO FOUND！"
            view.loadUrl("javascript:document.body.innerHTML=\"$data\"")
        }
    }

    // 视频全屏播放按返回页面被放大的问题
    override fun onScaleChanged(view: WebView, oldScale: Float, newScale: Float) {
        super.onScaleChanged(view, oldScale, newScale)
        if (newScale - oldScale > 7) {
            view.setInitialScale((oldScale / newScale * 100).toInt()) //异常放大，缩回去。
        }
    }

    /**
     * 网页里可能唤起其他的app
     */
    private fun handleOtherwise(url: String) {
        var appPackageName = ""
        // 支付宝支付
        if (url.contains("alipays")) {
            appPackageName = "com.eg.android.AlipayGphone"

            // 微信支付
        } else if (url.contains("weixin://wap/pay")) {
            appPackageName = "com.tencent.mm"

            // 京东产品详情
        } else if (url.contains("openapp.jdmobile")) {
            appPackageName = "com.jingdong.app.mall"
        } else {
            startActivity(url)
        }
        if (Tools.isApplicationInstall(webPageView!!.activity, appPackageName)) {
            startActivity(url)
        }
    }

    private fun startActivity(url: String) {
        try {
            // 用于DeepLink测试
            if (url.startsWith("will://")) {
                val uri = Uri.parse(url)
                Log.e(
                    "---------scheme",
                    uri.scheme + "；host: " + uri.host + "；Id: " + uri.pathSegments[0]
                )
            }
            val intent1 = Intent()
            intent1.action = "android.intent.action.VIEW"
            val uri = Uri.parse(url)
            intent1.data = uri
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            webPageView!!.activity.startActivity(intent1)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private var webPageView: IWebViewActivity?
        private get() = if (mIWebPageView == null) {
            throw RuntimeException("you must set IWevPageView")
        } else {
            mIWebPageView
        }
        set(mIWebPageView) {
            this.mIWebPageView = mIWebPageView
        }

    companion object {
        const val HTTP = "http:"
        const val HTTPS = "https:"
        const val APK = ".apk"
    }
}